// client/main.go
package main

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"

	"github.com/gorilla/websocket"
)

func main() {
	if len(os.Args) < 2 {
		fmt.Println("Usage: client <local_port>")
		os.Exit(1)
	}
	localPort := os.Args[1]

	// 1. 注册获取子域名
	// 替换原来的注册逻辑
	resp, err := http.Post("https://localhost:8443/register?port="+localPort, "", nil)
	if err != nil {
		log.Fatalf("❌ Failed to connect to tunnel server: %v\n", err)
	}
	defer resp.Body.Close() // 确保关闭

	if resp.StatusCode != http.StatusOK {
		log.Fatalf("❌ Server returned error: %s", resp.Status)
	}

	var reg struct {
		Subdomain string `json:"subdomain"`
		WsURL     string `json:"ws_url"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&reg); err != nil {
		log.Fatalf("❌ Failed to decode registration response: %v", err)
	}
	// 2. 连接 WebSocket 隧道
	dialer := &websocket.Dialer{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // 测试用
	}
	conn, _, _ := dialer.Dial(reg.WsURL, nil)
	defer conn.Close()

	// 3. 处理来自服务端的 HTTP 请求
	for {
		_, msg, err := conn.ReadMessage()
		if err != nil {
			break
		}

		var reqData map[string]interface{}
		json.Unmarshal(msg, &reqData)

		// 构造本地 HTTP 请求
		localReq, _ := http.NewRequest(
			reqData["method"].(string),
			"http://localhost:"+localPort+reqData["url"].(string),
			bytes.NewBufferString(reqData["body"].(string)),
		)
		for k, v := range reqData["header"].(map[string]interface{}) {
			localReq.Header.Set(k, v.([]interface{})[0].(string))
		}

		// 发送请求到本地服务
		client := &http.Client{}
		localResp, err := client.Do(localReq)
		if err != nil {
			continue
		}
		defer localResp.Body.Close()

		body, _ := io.ReadAll(localResp.Body)
		respData, _ := json.Marshal(map[string]interface{}{
			"status": localResp.StatusCode,
			"header": localResp.Header,
			"body":   string(body),
		})

		conn.WriteMessage(websocket.BinaryMessage, respData)
	}
}
